//
//  JXMeAddAddressViewController.m
//  JXAddressApp
//
//  Created by zhhw_home on 2018/11/3.
//  Copyright © 2018年 zhhw_home. All rights reserved.
//

#import "JXMeAddAddressViewController.h"
#import "JXPositionChooseViewController.h"
#import "NSDictionary+JSON.h"
#import "EgovaNetworking.h"
#import "QMUITips.h"
#import "NSDictionary+JSON.h"
#import "NSDictionary+Safe.h"
#import "UIView+QMUI.h"

@interface JXMeAddAddressViewController ()

@property (nonatomic, strong)   NSMutableDictionary    *item;

@end

@implementation JXMeAddAddressViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self){
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self){
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    
    self.title = @"新增地名";
    [self initializeForm];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(save)];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)setItem:(NSMutableDictionary *)item
{
    NSString *geometryJson = item[@"geometry"];
    NSDictionary *geometry = [NSDictionary JSONObject:geometryJson];
    NSArray *coordinates = geometry[@"coordinates"];
    CGFloat x = 0;
    CGFloat y = 0;
    if ([[coordinates firstObject] isKindOfClass:[NSArray class]]) {
        NSArray *point = [coordinates firstObject];
        
        x = [point[0] floatValue];
        y = [point[1] floatValue];
    }
    else {
        x = [coordinates[0] floatValue];
        y = [coordinates[1] floatValue];
    }
    
    _item = [item mutableCopy];
    _item[@"geometry"] = @{@"x":@(x),
                           @"y":@(y),
                           @"spatialReference":@{@"wkid":@(4326)}
                           };
    
}

- (void)initializeForm
{
    XLFormDescriptor * form;
    XLFormSectionDescriptor * section;
    XLFormRowDescriptor * row;
    
    form = [XLFormDescriptor formDescriptorWithTitle:@"Add Event"];
    
    // First section
    section = [XLFormSectionDescriptor formSection];
    [form addFormSection:section];
    
    // Title
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"creator" rowType:XLFormRowDescriptorTypeName title:@"真实姓名:"];
    row.required = YES;
    row.requireMsg = @"姓名不能为空";
    [row.cellConfigAtConfigure setObject:@"您的姓名" forKey:@"textField.placeholder"];
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"creatortel" rowType:XLFormRowDescriptorTypePhone title:@"联系电话:"];
    row.required = YES;
    row.requireMsg = @"电话不能为空";
    [row.cellConfigAtConfigure setObject:@"您的联系电话" forKey:@"textField.placeholder"];
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"creatoremail" rowType:XLFormRowDescriptorTypeEmail title:@"电子邮箱:"];
    row.required = YES;
    row.requireMsg = @"邮箱不能为空";
    [row.cellConfigAtConfigure setObject:@"您的电子邮箱" forKey:@"textField.placeholder"];
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"sysj" rowType:XLFormRowDescriptorTypeText title:@"地点名称:"];
    [row.cellConfigAtConfigure setObject:@"地点名称" forKey:@"textField.placeholder"];
    row.value = _item[@"sysj"]?:@"";
    row.required = YES;
    row.requireMsg = @"地点名称不能为空";
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"location" rowType:XLFormRowDescriptorTypeButton title:@"编辑位置:"];
//    row.required = YES;
//    row.requireMsg = @"位置不能为空";
    [row.cellConfig setObject:@(NSTextAlignmentNatural) forKey:@"textLabel.textAlignment"];
    [row.cellConfig setObject:@(UITableViewCellAccessoryDisclosureIndicator) forKey:@"accessoryType"];
    
    __typeof(self) __weak weakSelf = self;
    row.action.formBlock = ^(XLFormRowDescriptor * _Nonnull sender) {
        JXPositionChooseViewController *vc = [JXPositionChooseViewController new];
        vc.chooseBlock = ^(CLLocationCoordinate2D pos) {
            NSDictionary *geom = @{@"x":@(pos.longitude),
                                   @"y":@(pos.latitude),
                                   @"spatialReference":@{@"wkid":@(4326)}
                                   };
            
            weakSelf.item[@"geometry"] = geom;
            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"origin" rowType:XLFormRowDescriptorTypeText title:@"地名来历:"];
    row.required = YES;
    row.requireMsg = @"地名来历不能为空";
    [row.cellConfigAtConfigure setObject:@"此地的地名来历" forKey:@"textField.placeholder"];
    row.value = _item[@"origin"]?:@"";
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"mean" rowType:XLFormRowDescriptorTypeText title:@"地名含义:"];
    [row.cellConfigAtConfigure setObject:@"此地的地名含义" forKey:@"textField.placeholder"];
    row.value = _item[@"mean"]?:@"";
    row.required = YES;
    row.requireMsg = @"地名含义不能为空";
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"history" rowType:XLFormRowDescriptorTypeTextView title:@"历史沿革:"];
    row.value = _item[@"history"]?:@"";
    row.required = YES;
    row.requireMsg = @"历史沿革不能为空";
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"description" rowType:XLFormRowDescriptorTypeTextView title:@"地理描述:"];
    row.value = _item[@"description"]?:@"";
    row.required = YES;
    row.requireMsg = @"地理描述不能为空";
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"datasource" rowType:XLFormRowDescriptorTypeText title:@"资料来源:"];
    [row.cellConfigAtConfigure setObject:@"资料来源" forKey:@"textField.placeholder"];
    row.value = _item[@"datasource"]?:@"";
    row.required = YES;
    row.requireMsg = @"资料来源不能为空";
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"image" rowType:XLFormRowDescriptorTypeImage title:@"选择图片:"];
    row.height = 100.f;
    [section addFormRow:row];
    
    
    self.form = form;
}

- (void)save
{
    NSArray *errors = [self.form localValidationErrors:self];
    if (errors.count > 0) {
        NSError *error = [errors firstObject];
        
        [QMUITips showWithText:error.userInfo[NSLocalizedDescriptionKey] inView:self.view hideAfterDelay:1.5f];
        return;
    }
    
    if (self.item[@"geometry"] == nil) {
        [QMUITips showWithText:@"位置不能为空" inView:self.view hideAfterDelay:1.5f];
    }
    
    NSDictionary *values = [self formValues];
    NSString *url = @"http://wegis.net/demo/home/publicinteract/savepublicplaceinfo";
    NSDictionary *basefield = @{@"creator":values[@"creator"]?:@"",
                                @"creatortel":values[@"creatortel"]?:@"",
                                @"creatoremail":values[@"creatoremail"]?:@"",
                                @"placecode":_item[@"code"],
                                };
    
    NSDictionary *placefield = @{@"name": _item[@"name"]?:@"",
                                 @"sysj": values[@"sysj"]?:@"",
                                 @"telephone": values[@"creatortel"]?:@"",
                                 @"history": values[@"history"]?:@"",
                                 @"mean": values[@"mean"]?:@"",
                                 @"description": values[@"description"]?:@"",
                                 @"origin": values[@"origin"]?:@"",
                                 @"datasource": values[@"datasource"]?:@"",
                                 @"code": _item[@"code"]?:@"",
                                 @"geom": _item[@"geometry"]?:@{},
                                 @"editor": values[@"creator"]?:@""
                                 };
    
    [QMUITips showLoading:@"提交中，请稍候..." inView:self.view];
    
    [EgovaNetworking postWithUrl:url cache:NO params:@{@"basefield":[basefield JSONString], @"placefield":[placefield JSONString]} completed:^(NSInteger code, id data, NSString *msg) {
        if (code == 0) {
            NSNumber *problemcode = [data NoNullObjectForKey:@"problemcode"];
            
            [self uploadImages:[values NoNullObjectForKey:@"image"] problemcode:problemcode];
        }
        else {
            [QMUITips hideAllTipsInView:self.view];
        }
    }];
}
    

- (void)uploadImages:(UIImage*)image problemcode:(NSNumber*)problemcode
{
    if (!image) {
        [QMUITips hideAllTipsInView:self.view];
        [self performSelector:@selector(dismissVC) withObject:nil afterDelay:0.25];
        return;
    }
    
    NSDictionary *params = @{@"placecode":_item[@"code"],
                             @"type":@(5),
                             @"deleteflag":@(2),
                             @"placecode":@(5),
                             @"problemcode":problemcode
                             };
    
    [EgovaNetworking uploadWithImages:@[image]
                                  url:@"http://wegis.net/demo//home/govainfo/uploadplacemedia"
                                 name:@"attachrecs"
                             mimeType:@"image/jpeg"
                           parameters:params
                             progress:nil
                            completed:^(NSInteger code, id data, NSString *msg) {
                                [QMUITips hideAllTipsInView:self.view];
                                
                                if (code) {
                                    [self performSelector:@selector(dismissVC) withObject:nil afterDelay:0.25];
                                }
                           }];
}

- (void)dismissVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
